import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter_blog_manage_study/model/language_entity.dart';
import 'package:flutter_blog_manage_study/model/user_entity.dart';
import 'package:flutter_blog_manage_study/util/sp/sp_key.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

/// * 作者: Tao
/// * 日期: 2024/3/22
/// * 时间: 9:47
/// * 描述: SP工具类
class SPUtil {
  /// 删除用户信息
  static deleteUserInfo() {
    Get.find<SharedPreferences>().remove(SPKey.keyUserInfo);
  }

  /// 存储用户信息
  /// * [userInfo] 用户信息
  static putUserInfo(UserEntity userInfo) {
    Get.find<SharedPreferences>()
        .setString(SPKey.keyUserInfo, jsonEncode(userInfo.toJson()));
  }

  /// 获取用户信息
  static UserEntity? getUserInfo() {
    SharedPreferences sp = Get.find<SharedPreferences>();
    try {
      var json = sp.getString(SPKey.keyUserInfo);
      if (json == null) {
        return null;
      } else {
        return UserEntity.fromJson(jsonDecode(json));
      }
    } catch (e) {
      debugPrint(e.toString());
      return null;
    }
  }

  /// 存储语言
  /// * [language] 语言实体
  static updateLanguage(LanguageEntity language) {
    Get.find<SharedPreferences>().remove(SPKey.language);
    Get.find<SharedPreferences>()
        .setString(SPKey.language, jsonEncode(language.toJson()));
  }

  /// 获取语言
  /// * return [LanguageEntity] 语言实体
  static LanguageEntity? getLanguage() {
    SharedPreferences sp = Get.find<SharedPreferences>();
    try {
      var json = sp.getString(SPKey.language);
      if (json == null) {
        return null;
      } else {
        return LanguageEntity.fromJson(jsonDecode(json));
      }
    } catch (e) {
      debugPrint(e.toString());
      return null;
    }
  }
}
